package com.cnbbx.cnbbx_web.utils;

import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    private static final String USER_PWD_ENCODE_PREFIX = "THINK";

    /**
     * 用户密码加密
     */
    public static String encode(final String beforeEncode) {
        if (StringUtils.isBlank(beforeEncode)) {
            return beforeEncode;
        }
        return encryptMD5(USER_PWD_ENCODE_PREFIX + beforeEncode);
    }

    /**
     * md5加密
     */
    private static String encryptMD5(final String strInput) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(strInput.getBytes());
            byte b[] = md.digest();
            buf = new StringBuffer(b.length * 2);
            for (int i = 0; i < b.length; i++) {
                if (((int) b[i] & 0xff) < 0x10) buf.append("0");
                buf.append(Long.toHexString((int) b[i] & 0xff));
            }
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return buf == null ? null : buf.toString();
    }
}
